<template>
  <div class="app-container">
    <div class="filter-container">
      <el-select @change="handleChangeBOUDF" v-model="listQuery.U_BOUDF" placeholder="数据类型" clearable style="width: 150px;margin-right:10px" class="filter-item">
        <el-option v-for="item in BOUDFOptions" :key="item.Code" :label="item.Name" :value="item.Code" />
      </el-select>
      <el-select @change="handleChangeMEQU" v-model="curFilterMEQU" placeholder="设备编号" clearable style="width: 100px;margin-right:10px" class="filter-item">
        <el-option v-for="item in MEQUOptions" :key="item" :label="item" :value="item" />
      </el-select>
      <el-input placeholder="批号" v-model="curFilterLotId" clearable style="width: 120px;margin-right:10px" class="filter-item">
      </el-input>
      <el-input placeholder="产品" v-model="curFilterMatId" clearable style="width: 120px;margin-right:10px" class="filter-item">
      </el-input>
      <el-date-picker
        v-model="dtPicker"
        type="daterange"
        align="right"
        unlink-panels
        range-separator="至"
        start-placeholder="开始日期"
        end-placeholder="结束日期"
        class="filter-item"
        style="margin-right:10px"
        @change="datepickerChange($event)"
        :picker-options="pickerOptions">
      </el-date-picker>
      <el-button v-waves class="filter-item" type="primary" icon="el-icon-search" @click="handleFilter">
        查询
      </el-button>
      <el-button v-waves :loading="downloadLoading" class="filter-item" type="success" icon="el-icon-download" @click="handleDownload">
        导出
      </el-button>
    </div>

    <el-table v-loading="listLoading" ref="tb" :data="list" height="800" border fit highlight-current-row style="width: 100%;margin-bottom:30px;">
      <el-table-column align="center" label="单据号" width="100" fixed>
        <template slot-scope="scope">
          <span>{{ scope.row.DocEntry }}</span>
        </template>
      </el-table-column>

      <el-table-column width="100" align="center" label="设备编号" fixed>
        <template slot-scope="scope">
          <span>{{ scope.row.U_MEQU }}</span>
        </template>
      </el-table-column>

      <el-table-column width="150" align="center" label="批号" fixed>
        <template slot-scope="scope">
          <span>{{ scope.row.LotID }}</span>
        </template>
      </el-table-column>

      <el-table-column width="150" align="center" label="产品" fixed>
        <template slot-scope="scope">
          <span>{{ scope.row.U_ItemCode }}</span>
        </template>
      </el-table-column>

      <el-table-column width="100" align="center" label="产出数量" fixed>
        <template slot-scope="scope">
          <span>{{ scope.row.U_Qty }}</span>
        </template>
      </el-table-column>

      <el-table-column width="100" align="center" label="投入数量" fixed>
        <template slot-scope="scope">
          <span>{{ scope.row.U_InQty }}</span>
        </template>
      </el-table-column>

      <el-table-column width="100px" align="center" label="日期" fixed>
        <template slot-scope="scope">
          <span>{{ scope.row.CreateDate }}</span>
        </template>
      </el-table-column>

      <el-table-column width="100px" align="center" label="数据类型" fixed>
        <template slot-scope="scope">
          <span>{{ scope.row.DataType }}</span>
        </template>
      </el-table-column>

      <el-table-column v-for="item in cols" align="center" :label="item" width="100" >
        <template slot-scope="scope">
            <span>{{ scope.row.content[item] }}</span>
        </template>
      </el-table-column>

    </el-table>

    <pagination v-show="total>0" :total="total" :page.sync="listQuery.page" :limit.sync="listQuery.limit" @pagination="getList" />
  </div>
</template>

<script>
import { getAllMPCPendDataLists, getAllProductDataLists, fetchBOUDDs, fetchBOUDD1s, processBacktoPreviousMPCPs, fetchMLOOsByDocEntry, fetchEDCs, fetchMPCPendDataByBOUDFCode } from '@/api/res'
import { parseDate, dateAddDays, unique } from '@/utils'
import waves from '@/directive/waves'
import Pagination from '@/components/Pagination' // Secondary package based on el-pagination

export default {
  name: 'BoudfList',
  components: { Pagination },
  directives: { waves },
  data() {
    return {
      list: null,
      total: 0,
      listLoading: true,
      downloadLoading: false,
      cols: [],
      listQuery: {
        page: 1,
        limit: 20,
        U_BOUDF:'',
        Canceled:''
      },
      BOUDFOptions:[],
      mpcp1detail:[],
      curMPCP:'',
      dialogTableVisible:false,
      curFilterLotId:'',
      curFilterMatId:'',
      curFilterMEQU:'',
      MEQUOptions:[],
      dtPicker:['2023-08-01','2023-09-20'],
      pickerOptions: {
        shortcuts: [{
          text: '最近一周',
          onClick(picker) {
            const end = new Date();
            const start = new Date();
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 7);
            picker.$emit('pick', [start, end]);
          }
        }, {
          text: '最近一个月',
          onClick(picker) {
            const end = new Date();
            const start = new Date();
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 30);
            picker.$emit('pick', [start, end]);
          }
        }, {
          text: '最近三个月',
          onClick(picker) {
            const end = new Date();
            const start = new Date();
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 90);
            picker.$emit('pick', [start, end]);
          }
        }]
      }
    }
  },
  created() {
    const start = new Date();
    const end = new Date();
    start.setTime(start.getTime() - 3600 * 1000 * 24 * 30);
    this.dtPicker = [parseDate(start),parseDate(end)]

    fetchEDCs(this.listQuery).then(res=>{
      this.BOUDFOptions = res.flist
      console.log('success to get fetchEDCs',res)
      this.listLoading = false
      //this.getList()
    }).catch(err=>{
      this.listLoading = false
      console.log('failed to get fetchEDCs',err)
    })

  },
  methods: {
    handleDownload() {
      this.downloadLoading = true
      import('@/utils/Export2Excel').then(excel => {
        var tHeader = ['单据号', '设备编号', '批号', '产品', '产出数量', '投入数量', '日期', '数据类型']
        var filterVal = ['DocEntry', 'U_MEQU', 'LotID', 'U_ItemCode', 'U_Qty', 'U_InQty', 'CreateDate', 'DataType']
        tHeader.push(...this.cols)
        filterVal.push(...this.cols)
        var list = this.list

        list.forEach(item=>{
          var _content = item.content
          Object.keys(_content).forEach(col=>{
            item[col] = _content[col]
          })
        })

        //console.log('handleDownload------',tHeader,list)
        const data = this.formatJson(filterVal, list)

        var filename = this.BOUDFOptions.filter(v=>v.Code == this.listQuery.U_BOUDF)[0].Name+'_'
        filename +=this.dtPicker[0].replace(/-/g,'')+'_'+this.dtPicker[1].replace(/-/g,'')
        excel.export_json_to_excel({
          header: tHeader,
          data,
          filename: filename,
          autoWidth: true,
          bookType: 'xlsx'
        })
        this.downloadLoading = false
      })
    },
    formatJson(filterVal, jsonData) {
      return jsonData.map(v => filterVal.map(j => {
        if (j === 'timestamp') {
          return parseTime(v[j])
        } else {
          return v[j]
        }
      }))
    },
    datepickerChange(val){
      console.log('datepickerChange-------', val)
      if(val == null){
        this.dtPicker = ['','']
      }else{
        this.dtPicker = [parseDate(val[0]), parseDate(val[1])]
      }
    },

    handleChangeMEQU(val){
      this.curFilterMEQU = val != null ? val : ''
      console.log('handleChangeMEQU------',this.curFilterMEQU)
    },

    handleChangeBOUDF(val){
      this.listQuery.U_BOUDF = val
      console.log('handleChangeBOUDF------',this.listQuery.U_BOUDF)
    },

    handleFilter(){
      this.listQuery.page = 1
      console.log('handleFilter-----', this.listQuery)
      this.getList()
    },

    getList() {
      this.listLoading = true
      console.log(this.dtPicker)

      if(this.listQuery.U_BOUDF.trim().length == 0){
        this.$notify({ title: '提示', message: '数据类型不能为空, 请选择后再查询', type: 'warning', duration: 2000 })
        this.listLoading = false
        return
      }

      if(this.dtPicker.filter(v=>v.trim().length > 0).join(",").length == 0){
        this.$notify({ title: '提示', message: '日期不能为空, 请选择后再查询', type: 'warning', duration: 2000 })
        this.listLoading = false
        return
      }

      const start = parseDate(this.dtPicker[0]);
      const end = dateAddDays(1,parseDate(this.dtPicker[1]));


      var config = {
        from: start,
        to: end,
        Canceled: 'N',
        MEQG: this.listQuery.U_BOUDF.substr(0,2).toUpperCase(),
        MEQU: '',
        MPCO: 'end'
      }

      getAllMPCPendDataLists(config).then(resDt=>{
        var _mlist = []
        var clist = []

        resDt.forEach((item,idx)=>{
          item.CreateDate = item.CreateDate.substr(0,4)+'-'+item.CreateDate.substr(4,2)+'-'+item.CreateDate.substr(6,2)
          if(_mlist.length == 0 || _mlist.filter(v=>v.DocEntry == item.DocEntry).length == 0){
            item.ItemCode = item.U_ItemCode
            item.minDocEntry = item.DocEntry
            item.LotID = item.U_MLOO.trim()
            item.scbh = item.sc1.substr(1,item.sc1.length)
            item.scbh_docEntry = item.scDocEntry
            item.scbh_docEntry2 = item.scDocEntry2

            item.zlbh = item.zl1.substr(1,item.zl1.length)
            item.zlbh_docEntry = item.zlDocEntry
            item.zlbh_docEntry2 = item.zlDocEntry2

            _mlist.push(item)
          }else{
            var _eitem = _mlist.filter(v=>v.DocEntry == item.DocEntry)[0]
            _eitem.LotID = item.U_MLOO + ','+ item.U_MLOO.trim()
            if(item.U_ItemCode != _eitem.U_ItemCode){
              _eitem.U_ItemCode = item.U_ItemCode + ','+ item.U_ItemCode.trim()
              item.ItemCode = _eitem.U_ItemCode
            }

            if(idx == resDt.length-1){
              _mlist.push(item)
            }
          }

        })

        if(this.listQuery.U_BOUDF.indexOf('fqzl')>=0){
          var keepfqlots = _mlist.filter(v=>v.Canceled=='N' && v.U_OperParm=='keepfq').sort((a,b)=>{
            if(a.lot_id != b.lot_id) return a.lot_id.localeCompare(b.lot_id)
            return a.DocEntry.localeCompare(b.DocEntry)
          })

          var keepfqlist = []
          if(keepfqlots.length>0){
            keepfqlist.push(unique(keepfqlots.map(v=>v.lot_id)))
            var _minDocEntrys = []
            var _minDetails = []
            keepfqlist[0].forEach(item=>{
              var _minDoc = Math.min.apply(null,keepfqlots.filter(m=>m.lot_id == item).map(n=>n.DocEntry))
              _minDocEntrys.push(_minDoc)
              _minDetails.push(_mlist.filter(v=>v.DocEntry == _minDoc)[0])
            })
            keepfqlist.push(_minDocEntrys)
            keepfqlist.push(_minDetails)
            console.log('keepfqlist--------',keepfqlots.map(v=>v.lot_id),keepfqlots.map(v=>v.DocEntry),keepfqlist)

            _mlist = _mlist.map(item=>{
              var _minDocIdx = keepfqlist[0].indexOf(item.lot_id)
              if(_minDocIdx >= 0 && item.U_MEQG == 'FQ'){
                item.minDocEntry = keepfqlist[1][_minDocIdx]
                item.zlbh_docEntry = keepfqlist[2][_minDocIdx].zlbh_docEntry
              }
              return item
            })

          }
        }

        _mlist.forEach(item=>{
          item.DataType = '正面'
          item.content = {}
          item.U_BOUDF = this.listQuery.U_BOUDF.substr(2) == 'sc' ? item.sc1 : item.zl1
          item.BOUDD_DocEntry = this.listQuery.U_BOUDF.substr(2) == 'sc' ? item.scbh_docEntry : item.zlbh_docEntry
          clist.push(item)
          if((this.listQuery.U_BOUDF.substr(2) == 'sc' && item.schb_docEntry2 != undefined && item.schb_docEntry2 != '') || (this.listQuery.U_BOUDF.substr(2) == 'zl'  && item.zlhb_docEntry2 != undefined && item.zlhb_docEntry2 != '')){

            var _c = JSON.parse(JSON.stringify(item))
            _c.DataType = '反面'
            _c.content = {}
            _c.U_BOUDF = this.listQuery.U_BOUDF.substr(2) == 'sc' ? _c.sc2 : _c.zl2
            _c.BOUDD_DocEntry = this.listQuery.U_BOUDF.substr(2) == 'sc' ? _c.scbh_docEntry2 : _c.zlbh_docEntry2
            clist.push(_c)
          }
        })

        console.log('getAllMPCPendDataLists-----------',clist,clist.filter(v=>v.BOUDD_DocEntry != undefined && v.BOUDD_DocEntry!=''))

        var MEQUOptions =clist.map(v=>v.U_MEQU).sort()
        if(MEQUOptions.length>0){
          this.MEQUOptions = [...new Set(MEQUOptions)]
        }else{
          this.MEQUOptions = []
        }

        var flist = []
        getAllProductDataLists({
          BOUDF: this.listQuery.U_BOUDF,
          MEQU:'',
          from: start,
          to: dateAddDays(20,parseDate(this.dtPicker[1]))
        }).then(res=>{

          this.cols = res.cols.map(v=>v.U_Fd)
          var mpcpDocEntrys = unique(res.list.map(v=>v.U_RefEntry)).sort((a,b)=>a.localeCompare(b))

          res.list.sort((a,b)=>{
            if(a.DocEntry != b.DocEntry) return a.DocEntry.localeCompare(b.DocEntry)
            return a.LineId.localeCompare(b.LineId)
          }).forEach((item,idx)=>{
            var _contentItem = {LineId : item.LineId, U_A : item.U_A, U_B : item.U_B, U_D : item.U_D, U_N : item.U_N, U_Fd : item.U_Fd}
            if(flist.length == 0 || flist.filter(v=>v.DocEntry == item.DocEntry).length == 0){
              flist.push({
                DocEntry : item.DocEntry,
                U_BOUDF : item.U_BOUDF,
                U_RefCode : item.U_RefCode,
                U_RefType : item.U_RefType,
                U_RefEntry : item.U_RefEntry,
                Canceled : item.Canceled,
                CreateDate : item.CreateDate,
                DataType : item.U_RefType.substr(1) == item.U_BOUDF ? '正面' : '反面',
                content : [_contentItem]
              })
            }else{
              flist[flist.length-1].content.push(_contentItem)
            }

          })

          var _basecontent = {}
          this.cols.forEach(col=>{
            _basecontent[col.U_Fd] = ''
          })

          console.log('getAllProductDataLists-0----------',flist)

          clist.forEach(item=>{
            item.content = JSON.parse(JSON.stringify(_basecontent))
            flist.forEach(sub=>{

              if(item.DocEntry == sub.U_RefEntry && item.U_BOUDF == sub.U_RefType){
                res.cols.forEach(col=>{
                  sub.content.forEach(boudd=>{
                    if(col.U_Fd == boudd.U_Fd){
                      var U_fdTypeStr = 'U_' + col.U_FdType.substring(0,1).toUpperCase()
                      col.val = boudd[U_fdTypeStr]
                      if(col.U_FdType == 'B' && col.U_Decim != ''){
                        item.content[col.U_Fd] = (col.val*1).toFixed(col.U_Decim)
                      }else{
                        item.content[col.U_Fd] = boudd[U_fdTypeStr]
                      }

                    }
                  })
                })

                //console.log('getAllProductDataLists-----------',item.DocEntry,sub.U_RefType,_content)

              }

            })
          })

          if(this.curFilterMEQU.trim().length != 0){
            clist = clist.filter(v=>v.U_MEQU.indexOf(this.curFilterMEQU.trim())>=0)
          }

          if(this.curFilterLotId.trim().length != 0){
            clist = clist.filter(v=>v.LotID.indexOf(this.curFilterLotId.trim())>=0)
          }

          if(this.curFilterMatId.trim().length != 0){
            clist = clist.filter(v=>v.U_ItemCode.indexOf(this.curFilterMatId.trim())>=0)
          }

          console.log('getAllProductDataLists-1-----------',flist,clist)

          setTimeout(()=>{
            this.list = clist
            this.$refs.tb.doLayout();
            this.listLoading = false
          },2000)

        }).catch(err=>{console.log(err)})


      }).catch(err=>{console.log(err)})


/*
      fetchMPCPendDataByBOUDFCode({
        U_BOUDF: this.listQuery.U_BOUDF,
        U_MEQU:'',
        fromDate: start,
        toDate: end
      }).then(res=>{
        var flist = res.list
        this.cols = res.cols
        var MEQUOptions =flist.map(v=>v.U_MEQU).sort()
        if(MEQUOptions.length>0){
          this.MEQUOptions = [...new Set(MEQUOptions)]
        }else{
          this.MEQUOptions = []
        }
        console.log('fetchMPCPendDataByBOUDFCode-------',res,this.MEQUOptions)

        if(this.curFilterMEQU.trim().length != 0){
          flist = flist.filter(v=>v.U_MEQU.indexOf(this.curFilterMEQU.trim())>=0)
        }

        if(this.curFilterLotId.trim().length != 0){
          flist = flist.filter(v=>v.LotID.indexOf(this.curFilterLotId.trim())>=0)
        }

        if(this.curFilterMatId.trim().length != 0){
          flist = flist.filter(v=>v.ItemCode.indexOf(this.curFilterMatId.trim())>=0)
        }

        this.list = flist
        this.listLoading = false
      })
      */

    }
  }
}
</script>

<style scoped>
.edit-input {
  padding-right: 100px;
}
.cancel-btn {
  position: absolute;
  right: 15px;
  top: 10px;
}
</style>
